import {requestPayment} from './system-service';
import {getPaymentStatus, payCourse} from '../../data-model/model-pay';
import toast from '../../common/service/toast-service';
import {getUserInfo} from '../../common/service/user-service';
import {navigateTo} from '../../common/service/page-service';
import {PAY_ERROR} from '../constants';

/**
 * 通用支付服务
 * 抛给外部Promise对象
 * resolve 中为支付成功后的状态
 * reject 中为支付失败
 */
/**
 * 例子：
 * payment(1).then(data => {
            console.log('支付成功', data);
            data.isFree = true | false; 是否为免费
            data.payStatus = 1 已支付
            data.payStatus = 2 未支付
            data.payStatus = 3 支付中
        }).catch(cause => {
            console.log('支付失败', cause.errorCode);
            cause.errorCode = 1 USER_NOT_LOGIN
            cause.errorCode = 2 GET_PAY_OBJ_ERR
            cause.errorCode = 3 WX_PAY_ERR
            cause.errorCode = 4 GET_PAY_STATUS_ERR
        });
 */
exports.payment = function (courseId) {
    if (!getUserInfo()) {
        // 如果未登录
        navigateTo({url: '/pages/login/login'});
        console.log('用户未登录');
        return Promise.reject({errorCode: PAY_ERROR.USER_NOT_LOGIN});
    } else {
        // 已登录 执行支付
        toast.showLoading();
        return payCourse(courseId)
            .then(payJson => {
                let payParam = JSON.parse(payJson);
                console.log('获取的支付对象', payParam);
                return Promise.resolve(payParam);
            }).then(payParam => {
                if (payParam.paySuccess === 1) {
                    console.log('0元不需要支付');
                    return Promise.resolve(payParam);
                } else {
                    console.log('发起微信支付', payParam);
                    return requestPayment(payParam);
                }
            })
            .then(result => {
                toast.hideLoading();
                console.log('支付成功', result);
                // 获取支付状态
                return Promise.resolve({isFree: result.paySuccess === 1});
            })
            .catch(err => {
                toast.hideLoading();
                return Promise.reject(err);
            });
    }
};
